<template>
  <basic-container>
    <el-form ref="form" searchform :model="searchData" label-width="80px">
      <el-row>
        <el-col span="4" style="min-width:150px">
          <div class="text" style="width: 20%">文案:</div>
          <el-input
            placeholder="请输入文案"
            v-model="searchData.text"
            clearable style="width: 150px" size="mini" @keyup.enter.native="searchForm">
          </el-input>
        </el-col>
        <el-col span="5" style="min-width:150px">
          <div class="text" style="width: 20%">语言:</div>
          <el-select v-model="searchData.language" filterable placeholder="请选择" clearable size="mini" @keyup.enter.native="searchForm">
            <el-option
              v-for="item in languageList"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-col>
        <el-col span="5" style="min-width:150px">
          <div class="text" style="width: 30%">创建人:</div>
          <el-select v-model="searchData.createUser" placeholder="请选择" size="mini" clearable @keyup.enter.native="searchForm">
            <el-option
              v-for="item in createUserList"
              :key="item"
              :label="item.realName"
              :value="item.createUser">
            </el-option>
          </el-select>
        </el-col>
        <el-col span="6" style=";min-width:150px">
          <div class="text" style="width: 20%">创建时间:</div>
          <el-date-picker
            v-model="createTime"
            style="width: 192px; padding: 0; max-width: 98%"
            prefix-icon="null"
            type="daterange"
            :clearable="false"
            size="mini"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-col>
        <el-col span="3" style="min-width: 160px;display:flex;justify-content:flex-end;margin-left: 43px">
          <el-tooltip class="item" effect="dark" content="搜索" placement="top">
            <el-button id="id-offer-creative-button-searchForm" type="primary" size="small" @click="searchForm" style="margin-right: 0">搜索</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="清空" placement="top">
            <el-button id="id-offer-creative-button-emptyForm" type="primary" @click="emptyForm" size="mini">清空</el-button>
          </el-tooltip>
        </el-col>
      </el-row>
    </el-form>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               :row-class-name="rowClassNameFn"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @expand-change="expandChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <div style="display: flex">
          <el-button type="danger"
                     size="small"
                     plain
                     class="button-add-style"
                     style="min-width: 100px"
                     v-if="permission.documentlibrary_add"
                     @click="handleAdd">新增文案
          </el-button>
          <el-button type="danger"
                     size="small"
                     plain
                     style="min-width: 100px"
                     v-if="permission.documentlibrary_delete"
                     @click="handleDelete">删除文案
          </el-button>
          <el-upload
            ref="upload"
            class="upload-demo"
            action="/api/beetles-offer/documentlibrary/documents_import_xlsx"
            :headers="headerObj"
            :on-success="onSuccessFile"
            :on-error="onErrorFile"
            :before-remove="beforeRemove"
            accept=".xlsx,.xls"
            :limit="3"
            :data="{offerId:this.offer}"
            :on-exceed="handleExceed"
            :show-file-list="false">
            <el-button size="small" type="primary"
                       style="min-width: 100px;background-color: #ffffff;border-color: #c5c3f2;color: #907be3">导入</el-button>
          </el-upload>
          <el-button size="mini" style="border-color: #fed5bf;color: #fea373" @click="downloadTemplate">
            下载导入模板
          </el-button>
        </div>
      </template>
      <template slot-scope="{row,index}" slot="menu">
        <span v-if="row.hasOwnProperty('parent')"><i class="el-icon-edit" style="color: #1e9fff;cursor:pointer;"
                                                     @click="upData(row)"></i></span>
        <span v-if="row.hasOwnProperty('parent')"><i class="el-icon-delete"
                                                     style="margin-left: 25px;color: #1e9fff;cursor: pointer"
                                                     @click="rowDel(row)"></i></span>
      </template>
      <template slot="expand" slot-scope="{row}">
        <p v-for="(item,index) in row.content2" :key="index">
          <span>{{ item.text }}</span><span>{{ item.language }}</span>
        </p>

      </template>
    </avue-crud>
    <el-drawer
      ref="drawer"
      :title="title"
      size="60%"
      :visible.sync="drawer"
      direction="rtl"
      :wrapperClosable="false"
      :close-on-press-escape="false"
      :modal="true"
      :append-to-body="true"
      :before-close="handleClose">
      <el-divider></el-divider>
      <el-form :model="addData" :rules="rules" ref="addDataRef">
          <div style="margin-top: 15px;margin-left: 20px;display: flex">
            <el-form-item prop="language">
              <el-select v-model="addData.language" placeholder="请选择">
                <el-option v-for="(item,index) in languageList" :key="index" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="cs-input" prop="text">
              <el-input  style="height: 40px;display:inline;" type="textarea" autosize v-model="addData.text"/>
            </el-form-item>
          </div>
          <div style="margin-top: 15px;margin-left: 20px;display: flex" v-for="(item,index) in addData.children"
               :key="index">
            <el-form-item :prop="'children.'+index+'.language'">
              <el-select v-model="item.language" placeholder="请选择">
                <el-option v-for="(item,index) in languageList" :key="index" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="cs-input" :prop="'children.'+index+'.text'">
              <el-input type="textarea" autosize v-model="item.text"/>
            </el-form-item>
            <div style="width: 20%;cursor:pointer"><i class="el-icon-close" style="margin-top: 10px"
                                       @click="delDrawerRow(index)"></i></div>
          </div>
      </el-form>
      <div style="margin-top: 20px;margin-left: 20px;">
        <i class="el-icon-circle-plus-outline" style="color: #34acff;font-size: 15px;cursor:pointer;"
           @click="addSelect()"></i>
        <span style="margin-left: 15px;color:#34acff;cursor:pointer;" @click="addSelect()">添加</span>
      </div>
      <div class="div-button">
        <el-button type="primary" plain size="mini" @click="rowSave">保存</el-button>
        <el-button type="primary" plain size="mini" @click="cancel">取消</el-button>
      </div>
    </el-drawer>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/offer/documentlibrary";
import {mapGetters} from "vuex";
import {getSysDictList} from "../../api/system/dict";
import {transformObjectList} from "../../util/util";
import {deepClone} from '@/util/util';
import website from '@/config/website';
import {Base64} from "js-base64";
import {getToken} from "../../util/auth";
import Moment from "moment";
import {getCreateUser} from "../../api/offer/documentlibrary";
import {createEventHandler} from "../../util/events";

export default {
  data() {
    return {
      createUserList: [],
      emptyIcon: 'el-icon-delete',
      createTime: [],
      pickerOptions: {
        // disabledDate(time) {
        //   return time.getTime()>Moment(new Date()).subtract(1,'days')
        // },
        shortcuts: [{
          text: '昨日',
          onClick(picker) {
            const start = Moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD')
            picker.$emit('pick', [start, start])
          }
        }, {
          text: '当周',
          onClick(picker) {
            const weekOfDay = Moment().format('E')
            const start = Moment().subtract(weekOfDay - 1, 'days').format('YYYY-MM-DD')
            const end = Moment().add(7 - weekOfDay, 'days').format('YYYY-MM-DD')
            picker.$emit('pick', [start, end])
          },
        }, {
          text: '上周',
          onClick(picker) {
            const weekOfday = parseInt(Moment().format('E'))
            const start = Moment().subtract(weekOfday - 1 + 7, 'days').format('YYYY-MM-DD')
            const end = Moment(new Date()).subtract(weekOfday, 'days').format('YYYY-MM-DD')
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '当月',
          onClick(picker) {
            const end = Moment(new Date()).subtract(-1).format('YYYY-MM-DD')
            const start = Moment().startOf('months').format('YYYY-MM-DD')
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '上月',
          onClick(picker) {
            const start = Moment().subtract('month', 1).format('YYYY-MM') + '-01'
            const end = Moment(start).subtract('month', -1).add('days', -1).format('YYYY-MM-DD')
            picker.$emit('pick', [start, end])
          }
        }]
      },
      searchData: {
        text: '',
        language: '',
        createUser: '',
        startDate: '',
        endDate: '',
      },
      headerObj: {
        Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
        'Blade-Auth': 'bearer ' + getToken()
      },
      fileList: [],
      title: "新增文案",
      expendList: [{id: 3, text: "aaa", language: "222"}],
      languageList: [],
      addData: {
        text: '',
        language: '',
        children: [],
      },
      children: [],
      drawer: false,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        reserveSelection: true,
        tip: false,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        defaultExpandAll: false,
        column: [
          {
            label: "文案",
            prop: "text",
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入文案",
              trigger: "blur"
            }]
          },
          {
            label: "语言",
            prop: "language",
            rules: [{
              required: true,
              message: "请输入语言",
              trigger: "blur"
            }]
          },
          {
            label: "创建人",
            prop: "realName",
            rules: [{
              required: true,
              message: "请输入创建人",
              trigger: "blur"
            }]
          },
          {
            label: "创建时间",
            prop: "createTime",
            rules: [{
              required: true,
              message: "请输入创建时间",
              trigger: "blur"
            }]
          },
        ]
      },
      data: [],
      rowData: [],
      // 添加表单验证规则
      rules: {
        language: [
          {required: true, message: '请至少选择一个语言', trigger: 'blur'}
        ],
        text: [
          {required: true, message: '文案不能为空', trigger: 'blur'}
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["permission", "offer"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.documentlibrary_add, false),
        viewBtn: this.vaildData(this.permission.documentlibrary_view, false),
        delBtn: this.vaildData(this.permission.documentlibrary_delete, false),
        editBtn: this.vaildData(this.permission.documentlibrary_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  created() {
    let self = this;
    this.eventHandler = createEventHandler("offerCenter").addListener(
      (event) => {
        if (
          event.message == "offerChanged" &&
          event.offerId &&
          event.offerId !== ""
        ) {
          self.offer = event.offerId;
          self.refreshChange();
        }
      }
    );
    getCreateUser().then(res =>{
      this.createUserList = res.data.data
    })
    getSysDictList('language').then(map => {
      let languageData = transformObjectList(map['language'], [
        {from: 'dictValue', to: 'label'},
      ])
      for (let key in languageData) {
        this.languageList.push(languageData[key].label)
      }

    })
  },
  methods: {
    downloadTemplate(){
      let link = document.createElement("a")
      console.log(link)
      link.style.display = "none"
      link.href = "https://ads4each-image-full-size.obs.cn-east-3.myhuaweicloud.com/%E5%A4%9A%E8%AF%AD%E8%A8%80%E6%96%87%E6%A1%88%E5%BA%93%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
      document.body.appendChild(link)
      link.click()
    },
    handleClose() {
      this.drawer = false
      this.addData = {
        text: "",
        language: "",
        children: []
      }
    },
    onErrorFile() {
      this.$message.error("导入失败，请检查导入文件格式是否正确")
      this.$refs.upload.clearFiles();
      this.refreshChange()
    },
    onSuccessFile() {
      this.$message.success("导入成功")
      this.$refs.upload.clearFiles();
      this.refreshChange()
    },
    //搜索
    searchForm() {
      this.refreshChange()
    },
    //清空
    emptyForm() {
      this.searchData = {
        text: '',
        language: '',
        createUser: '',
        startDate: '',
        endDate: '',
      }
      this.createTime = []
      this.refreshChange()
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    delDrawerRow(index) {
      this.addData.children.splice(index, 1)
    },
    cancel() {
      this.drawer = false
      this.addData = {
        text: "",
        language: "",
        children: []
      }
    },
    upData(row) {
      this.rowData = []
      this.rowData = row
      this.title = "编辑文案"
      this.drawer = true
      let rowData = deepClone(row)
      this.addData.text = rowData.text
      this.addData.language = rowData.language
      this.addData.children = rowData.children
    },
    addSelect() {
      let index = this.addData.children.length
      this.rules[`children.${index}.text`] = [
        {required: true, message: '文案不能为空', trigger: 'blur'}
      ]
      this.rules[`children.${index}.language`] = [
        {required: true, message: '请至少选择一个语言', trigger: 'change'}
      ]
      this.$refs.form.validate((valid) => {
        if (valid) {
          let item = {
            id: +new Date(),
            text: '',
            language: '',
          }
          this.addData.children.push(item)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      console.log(this.rules)
    },
    handleAdd() {
      this.drawer = true
      this.title = "新增文案"
    },
    rowSave() {
      this.$refs.addDataRef.validate(  async vaild => {
        if (!vaild) return
        this.drawer = false
        // let arrList = {id: +new Date(), text: this.addData.text, language: this.addData.language, children: this.children}
        this.addData.id = +new Date()
        let data = JSON.stringify(this.addData)
        if (this.title === "编辑文案") {
          this.rowData.content = data
          let tableData = {
            content: this.rowData.content,
            id: this.rowData.id
          }
          await add(tableData)
          this.onLoad(this.page);
        } else if (this.title === "新增文案") {
          let ls = {
            content: data,
            offerId: this.offer
          }
          await add(ls)
          const res = await getCreateUser()
          this.createUserList = res.data.data
          this.onLoad(this.page);
        }
        this.addData = {
          text: "",
          language: "",
          children: []
        }
      })

    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.createTime != null) {
        this.searchData.startDate = this.createTime[0]
        this.searchData.endDate = this.createTime[1]
      }
      this.query = this.searchData
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query), this.offer).then(res => {
        const data = res.data.data;
        let tableData = []
        res.data.data.records.forEach(item => {
          let content = JSON.parse(item.content)
          content.id = item.id
          content.parent = 'parent'
          content.realName = item.realName
          content.createTime = item.createTime
          tableData.push(content)
        })
        this.data = tableData;
        this.page.total = data.total;
        this.loading = false;
        this.selectionClear();
      });
    },
    expandChange(row, expendList) {

    },
    // 清楚子行的多选框
    rowClassNameFn({row}) {
      if (!row.hasOwnProperty('parent')) {
        return 'hiddenSelect'
      }
    }
  }
};
</script>

<style scoped>
.button-add-style {
  border-color: #1e88fd;
  color: #1684fd;
  background-color: #ffffff;
  min-width: 80px;
}

.button-Import-style {
  border-color: #9d99e9;
  color: #a17be5;
  background-color: #ffffff;
  min-width: 80px;
}

/deep/ .el-drawer__header > :first-child {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  color: #101010;
  font-weight: 500;
  letter-spacing: 3px;
}

/deep/ .el-drawer__header {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  color: #72767b;
  display: flex;
  margin-bottom: 10px;
  padding: 20px 20px 0;
}

/deep/ .el-input--suffix .el-input__inner {
  padding-right: 30px;
  width: 145px;
}

.div-button {
  margin-top: 80px;
  display: flex;
  justify-content: center;
}

/deep/ .el-input-group > .el-input__inner {
  vertical-align: middle;
  display: table-cell;
  width: 380px;
}
</style>

<style lang="scss" scoped>
::v-deep .hiddenSelect {
  td:first-child {
    .cell {
      visibility: hidden;
    }
  }
}

.cs-input {
  width: 70%;
}

.search-div {
  width: 80%;
  height: 200px;
  background-color: #ffffff;
  margin-left: 90px;
  margin-bottom: 10px;
}
::v-deep .el-textarea__inner{
  min-height: 40px !important;
}
/deep/ .el-drawer.rtl{
  overflow: scroll;
}
/deep/ .el-date-editor .el-range-input, .el-date-editor .el-range-separator {
  height: auto;
  overflow: hidden;
  margin-left: -8px;
}
/deep/ .el-pagination .el-select .el-input .el-input__inner {
  margin-left: 0px;
  padding-right: 43px;
  border-radius: 3px;
  width: 112px;
}
/deep/ .el-icon-arrow-up:before {
  margin-left: -80px;
  content: "\e6e1";
}
/deep/ .el-icon-arrow-up:before {
  content: "\e6e1";
  margin-right: -85px;
}
</style>
